package com.duqc.freemarker;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedWriter;
import java.io.File;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.util.stream.Collectors;

import static java.sql.DriverManager.getConnection;

/**
 * @ClassName TableInfoGenerator
 * @Description TableInfoGenerator
 * @Author duqc
 * @Date 2022/10/12
 **/
@Slf4j
public class DictInfoGenerator {

    /**
     * 代码根路径
     */
    private static final String PATH = System.getProperty("user.dir");


    /**
     * 生成word文件
     *
     * @param dataMap      word中需要展示的动态数据，用map集合来保存
     * @param templateName word模板名称，例如：test.ftl
     * @param filePath     文件生成的目标路径，例如：D:/wordFile/
     * @param fileName     生成的文件名称，例如：test.doc
     */
    @SneakyThrows
    public static void createWord(Map dataMap, String templateName, String filePath, String fileName) {
        try {
            //创建配置实例
            Configuration configuration = new Configuration(Configuration.getVersion());
            //设置编码
            configuration.setDefaultEncoding("UTF-8");
            //ftl模板文件
            configuration.setDirectoryForTemplateLoading(new File(String.format("%s\\src\\main\\resources\\module", PATH)));
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            //获取模板
            Template template = configuration.getTemplate(templateName);
            //输出文件
            File outFile = new File(filePath + File.separator + fileName);
            //如果输出目标文件夹不存在，则创建
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(outFile.toPath()), StandardCharsets.UTF_8));
            //生成文件
            template.process(dataMap, out);
            //关闭流
            out.flush();
            out.close();
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        }
    }

    private void generator() {
        String url = "jdbc:mysql://192.168.6.244:11123/tech_portal?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&rewriteBatchedStatements=true&allowMultiQueries=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "poEV56Gjhqq4";
        Properties props = new Properties();
        props.setProperty("remarks", "true");
        props.setProperty("user", username);
        props.setProperty("password", password);
        props.setProperty("useInformationSchema", "true");
        String commentSql = "select t1.name,t1.code,sdt.type_name \n" +
                "from sys_dict t1 \n" +
                "left join sys_dict_type sdt  on t1.dic_type_id  = sdt.id where t1.state = 0 and  sdt.state = 0 and t1.visible = 1";
        try (Connection connection = getConnection(url, props);
             PreparedStatement preparedStatement = connection.prepareStatement(commentSql)) {
            ResultSet resultSet = preparedStatement.executeQuery();
            List<DictInfo> dictInfoList = new ArrayList<>();
            while (resultSet.next()) {
                DictInfo dictInfo = new DictInfo();
                dictInfo.setCode(resultSet.getString("code"));
                dictInfo.setName(resultSet.getString("name"));
                dictInfo.setTypeName(resultSet.getString("type_name"));
                dictInfoList.add(dictInfo);
            }
            Map<String, List<DictInfo>> collect = dictInfoList.stream().collect(Collectors.groupingBy(DictInfo::getTypeName));
            String filePath = "D:\\";
            String fileOnlyName = "dict.doc";
            Map<String, Map<String, List<DictInfo>>> map = new HashMap<>();
            map.put("collect", collect);
            DictInfoGenerator.createWord(map, "dict.ftl", filePath, fileOnlyName);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        new DictInfoGenerator().generator();
    }

}
